<?php 
class Code{

private $img; //验证码图片
private $width;//验证码图片宽度
private $height;//验证码图片高度
private $num;//验证码数量
private $seed;//种子
private $font;//字体大小
private $fontfile;//字体文件位置
private $code;//存放生成的验证码

public function __construct($width=NULL,$height=NULL,$num=NULL,$font=NULL,$fontfile=NULL,$seed=NULL){
	$this->width = is_null($width)?C('CODE_WIDTH'):$width;
	$this->height = is_null($height)?C('CODE_HEIGHT'):$height;
	$this->num = is_null($num)?C('CODE_COUNT'):$num;
	$this->seed = is_null($seed)?C('CODE_SEEK'):$seed;
	$this->font = is_null($font)?C('CODE_FONTSIZE'):$font;
	$this->fontfile = is_null($fontfile)?FONT_PATH.'/font.ttf':$fontfile;
	$code = "";
}


//显示函数
public function show(){
	$this->code ="";
	$this->createBg();
	$this->write();
	$this->disturb();
	$this->perish();
}
public function createBg(){
	//发送头部
	header('Content-type:image/png');
	//创建画布
	$this->img = imagecreatetruecolor($this->width, $this->height);
	//设置颜色及填充
	$white = imagecolorallocate($this->img, 255, 255, 255);
	imagefill($this->img, 0, 0, $white);
}
public function write(){
	//写字
//	几位验证码就循环几次
	for($i=0;$i<$this->num;$i++){
//		先选出验证码的颜色
		$color = imagecolorallocate($this->img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
//		再从种子中随机选出一位验证码
		$code = $this->seed[mt_rand(0, mb_strlen($this->seed)-1)];
		//将循环出的验证码存放到变量中
		$this->code .= $code;
		//		设置验证码在图片上的坐标 x y 
		$x = $i * ($this->width/$this->num)+10;
		$y = ($this->height+$this->font)/2;
//		写入到图片上
		imagettftext($this->img, $this->font, mt_rand(-45, 45), $x, $y, $color, $this->fontfile, $code);
	}
}
public function disturb(){
	//干扰
	$area = $this->width*$this->height;
	//画线
	for($i=0;$i<$area*0.002;$i++){
		$color = imagecolorallocate($this->img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
		imageline($this->img, mt_rand(0, $this->width), mt_rand(0, $this->height), mt_rand(0, $this->width), mt_rand(0, $this->height), $color);
	}
	//画点
	for($i=0;$i<$area*0.2;$i++){
		$color = imagecolorallocate($this->img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
		imagesetpixel($this->img, mt_rand(0,$this->width), mt_rand(0,$this->height), $color);
	}
	//画圆
	for($i=0;$i<$area*0.001;$i++){
		$color = imagecolorallocate($this->img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
		$wh = mt_rand(0, 30);
		imageellipse($this->img, mt_rand(0, $this->width), mt_rand(0, $this->height), $wh, $wh, $color);
	}
	
}
public function perish(){
	//输出
	imagepng($this->img);
	//销毁
	imagedestroy($this->img);
}
	
	
	
	
	
	
	
	
	
	
	
	
}
 ?>